package com.jspgou.cms.action.store;

import static com.jspgou.cms.Constants.STORE_SYS;
import static com.jspgou.common.page.SimplePage.cpn;
import static com.jspgou.common.web.Constants.LIST_SPLIT;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.jspgou.cms.Constants;
import com.jspgou.cms.entity.Brand;
import com.jspgou.cms.entity.Category;
import com.jspgou.cms.entity.Exended;
import com.jspgou.cms.entity.Payment;
import com.jspgou.cms.entity.Product;
import com.jspgou.cms.entity.ProductExended;
import com.jspgou.cms.entity.ProductExt;
import com.jspgou.cms.entity.ProductFashion;
import com.jspgou.cms.entity.ProductStandard;
import com.jspgou.cms.entity.ProductType;
import com.jspgou.cms.entity.ProductTypeProperty;
import com.jspgou.cms.entity.Shipping;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.StandardType;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.lucene.LuceneProductSvc;
import com.jspgou.cms.manager.BrandMng;
import com.jspgou.cms.manager.CategoryMng;
import com.jspgou.cms.manager.ExendedMng;
import com.jspgou.cms.manager.PaymentMng;
import com.jspgou.cms.manager.ProductFashionMng;
import com.jspgou.cms.manager.ProductMng;
import com.jspgou.cms.manager.ProductStandardMng;
import com.jspgou.cms.manager.ProductTagMng;
import com.jspgou.cms.manager.ProductTypeMng;
import com.jspgou.cms.manager.ProductTypePropertyMng;
import com.jspgou.cms.manager.PromoteMng;
import com.jspgou.cms.manager.ShippingMng;
import com.jspgou.cms.manager.StandardMng;
import com.jspgou.cms.manager.StandardTypeMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.CookieUtils;
import com.jspgou.common.web.RequestUtils;
import com.jspgou.common.web.ResponseUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;

@Controller
public class ProductFroAct {
	private static final Logger log = LoggerFactory.getLogger(ProductFroAct.class);
	
	/**
	 * 商品添加页
	 */
	public static final String PRODUCT_ADD = "tpl.productAdd";
	/**
	 * 商品修改页
	 */
	public static final String PRODUCT_EDIT = "tpl.productEdit";
	/**
	 * 商品列表页
	 */
	public static final String PRODUCT_LIST = "tpl.productList";
	/**
	 * 商品类别页
	 */
	public static final String PRODUCT_CATEGORY = "tpl.productCategory";
	/**
	 * 店铺注册页
	 */
	public static final String STORE_REGISTRER = "tpl.storeRegister";
	/**
	 * 商品规格页
	 */
	public static final String PRODUCT_STANDARDTYPES = "tpl.productStandardTypes";
	/**
	 * 已卖完商品页
	 */
	public static final String PRODUCT_SOLD_LIST = "tpl.productSoldList";
	
	@RequestMapping(value = "/product/v_list*.jspx")
	public String list(String cl,Long ctgId,Boolean isOnSale,
			Long typeId,Double startSalePrice,Double endSalePrice,
			Integer startStock,Integer endStock,Integer pageNo, 
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return "redirect:../login.jspx";
		}
		Store store=member.getStore();
		if(store==null){
			return "redirect:registerStore.jspx";
		}
		String productName = RequestUtils.getQueryParam(request, "productName");
		productName = StringUtils.trim(productName);
		String brandName = RequestUtils.getQueryParam(request, "brandName");
		brandName = StringUtils.trim(brandName);
		Pagination pagination = manager.getPage(web.getId(),null,store.getId(),
				productName,brandName,null,isOnSale,null,null,typeId,
				startSalePrice,endSalePrice,startStock,endStock,cpn(pageNo), CookieUtils.getPageSize(request));
		model.addAttribute("productName", productName);
		model.addAttribute("brandName",brandName);
		model.addAttribute("isOnSale", isOnSale);//上架
		model.addAttribute("typeId",typeId);
		model.addAttribute("startSalePrice", startSalePrice);
		model.addAttribute("endSalePrice", endSalePrice);
		model.addAttribute("startStock",startStock);
		model.addAttribute("endStock", endStock);
		model.addAttribute("pagination",pagination);
		model.addAttribute("ctgId", ctgId);
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("cl", cl);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,PRODUCT_LIST), request);
	}
	
	@RequestMapping(value = "/product/sold*.jspx")
	public String sold(String cl,Long paymentId,Long shippingId,String code,
			String userName,String startTime,String endTime,Integer status,
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return "redirect:../login.jspx";
		}
		Store store=member.getStore();
		if(store==null){
			return "redirect:registerStore.jspx";
		}
		if(StringUtils.isBlank(startTime)){
			model.addAttribute("startTime", null);
		}else{
		  model.addAttribute("startTime", startTime);
		}
		if(StringUtils.isBlank(endTime)){
			model.addAttribute("endTime", null);
		}else{
		  model.addAttribute("endTime", endTime);
		}
		List<Shipping> shippingList = shippingMng.getList(web.getId(),null,null, true);
		List<Payment> paymentList = paymentMng.getList(web.getId(), true);
		model.addAttribute("paymentList", paymentList);
		model.addAttribute("shippingList", shippingList);
		model.addAttribute("code", code);
		model.addAttribute("paymentId", paymentId);
		model.addAttribute("shippingId", shippingId);
		model.addAttribute("userName", userName);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("status", status);
		model.addAttribute("store", store);
		model.addAttribute("cl", cl);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,PRODUCT_SOLD_LIST), request);
	}
	
	@RequestMapping(value = "/product/v_category.jspx",method = RequestMethod.GET)
	public String category(String cl,HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		//用户没有注册店铺，跳转到店铺注册页
		if(store==null){
			return "redirect:registerStore.jspx";
		}
		//没有判断子目录是否存在
		List<Category> clist=categoryMng.getTopList(web.getId());
		model.addAttribute("cl", cl);
		model.addAttribute("clist", clist);
		model.addAttribute("store", store);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,
					PRODUCT_CATEGORY), request);
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/product/v_add.jspx")
	public String add(Long categoryId,Long brandId,
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		//用户没有注册店铺，跳转到店铺注册页
		if(store==null){
			return "redirect:registerStore.jspx";
		}
		if(categoryId==null){
			return "redirect:v_category.jspx";
		}
		Category category=categoryMng.findById(categoryId);
		List<ProductTypeProperty> itemList = productTypePropertyMng.getList(category.getType().getId(), false);
		List<StandardType> standardTypeList =standardTypeMng.getList(category.getId());
		List<ProductType> typeList = productTypeMng.getList(1L);
		List<Brand> brandList = brandMng.getAllList();
		model.addAttribute("brandList", brandList);
		model.addAttribute("typeList", typeList);
		model.addAttribute("ctgId", categoryId);
		model.addAttribute("category", category);
		model.addAttribute("categoryList", categoryMng.getListForProduct(SiteUtils.getWebId(request), categoryId));
		model.addAttribute("tagList", productTagMng.getList(SiteUtils.getWebId(request)));
		model.addAttribute("standardTypeList", standardTypeList);
		model.addAttribute("itemList", itemList);
		List<Exended> exendeds = exendedMng.getList(category.getType().getId());
		Map map= new HashMap(); 
		Map map1= new HashMap(); 
		int num = exendeds.size();
	    for(int i=0;i<num;i++){
			map.put(exendeds.get(i).getId().toString(), exendeds.get(i).getItems());
			map1.put(exendeds.get(i).getId().toString(), exendeds.get(i));
		}
		model.addAttribute("map", map);
		model.addAttribute("map1", map1);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,PRODUCT_ADD), request);
	}
	
	
	private Integer getstockCounts(Integer stockCounts[]){
		Integer stockCount =0;
		if(stockCounts!=null){
			for(Integer s:stockCounts){
				stockCount  = stockCount + s;
			}
		}
		return stockCount;
	}
	
	
	@RequestMapping(value = "/product/o_save.jspx",method = RequestMethod.POST)
	public String save(Product bean, ProductExt ext,Long ctgId,Long brandId,Long[] storeCategoryIds,
			Long[] tagIds, String productKeywords,String[] nature,Long[] picture,String[] colorImg,Long[] character, String rightlist,String combinationrightlist,
			@RequestParam(value = "file", required = false) MultipartFile file,
			String fashionSwitchPic[],Boolean[] isDefaults,Long[] colors,Long[] measures,Long promoteId,Integer stockCounts[],
			Integer[] saleCounts,Double[] salePrices,Double[] marketPrices,Double[] costPrices,String text,
			HttpServletRequest request,HttpServletResponse response, ModelMap model) throws IOException {
		
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		//用户没有注册店铺，跳转到店铺注册页
		if(store==null){
			return "redirect:registerStore.jspx";
		}
		productKeywords = StringUtils.replace(productKeywords, MessageResolver
				.getMessage(request, "product.keywords.split"), LIST_SPLIT);
		String[] keywords = StringUtils.split(productKeywords, LIST_SPLIT);
		Map<String, String> exended = RequestUtils.getRequestMap(request, "exended_");
	    List li=new ArrayList(exended.keySet());
	    String[] names = new String[li.size()];
	    String[] values =  new String[li.size()];
	    for(int i=0;i<li.size();i++){
	    	names[i]=(String) li.get(i);
	    	values[i]=exended.get(li.get(i));
	    }
	    bean.setStore(store);
	    bean.setAttr( RequestUtils.getRequestMap(request, "attr_"));
	    if(stockCounts!=null){
	    	bean.setStockCount(getstockCounts(stockCounts));
	    }
		bean = manager.save(bean, ext, web.getId(), ctgId, brandId, storeCategoryIds,tagIds,promoteId,
				keywords,names,values,fashionSwitchPic,file);
		manager.addCorrelation(bean,getProductIds(rightlist));
		manager.addCombination(bean, getProductIds(combinationrightlist));
		 if(picture!=null){
				for(int i =0;i<picture.length;i++){
					ProductStandard ps=new ProductStandard();
					ps.setImgPath(colorImg[i]);
					ps.setType(standardMng.findById(picture[i]).getType());
					ps.setProduct(bean);
					ps.setStandard(standardMng.findById(picture[i]));
					ps.setDataType(true);
					productStandardMng.save(ps);
				}
			}
		   if(character!=null){
			   for(int i =0;i<character.length;i++){
					ProductStandard ps=new ProductStandard();
					ps.setType(standardMng.findById(character[i]).getType());
					ps.setProduct(bean);
					ps.setStandard(standardMng.findById(character[i]));
					ps.setDataType(false);
					productStandardMng.save(ps);
				}
		    }
		saveProductFash(bean,nature,isDefaults,stockCounts,salePrices,marketPrices,costPrices);
		String path = servletContext.getRealPath(Constants.LUCENE_JSPGOU);
		Directory dir = new SimpleFSDirectory(new File(path));
		try{
	        luceneProductSvc.createIndex(bean,dir);
	    } catch (IOException e) {
		     log.error("", e);
	    }
		return "redirect:v_category.jspx";
	}
	
	private Object fashionSwitchPic(int i) {
		// TODO Auto-generated method stub
		return null;
	}

	// AJAX请求，不返回页面
			@RequestMapping("/product/v_search.jspx")
			public void search(Long storeId,Long correlationtypeId,Long correlationbrandId,String correlationproductName,
					HttpServletRequest request, HttpServletResponse response,
					ModelMap model) {
				ShopMember member=CmsUtils.getMember(request);
				Store store=member.getStore();
				List<Product> list = manager.getList(store.getId(),correlationtypeId, correlationbrandId, correlationproductName);
				JSONObject json=new JSONObject();
				try {
					for (int i=0 ,j=list.size(); i < j; i++) {
							json.append(list.get(i).getId() + "", list.get(i).getName());
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				ResponseUtils.renderJson(response, json.toString());
			}
			
			@RequestMapping("/product/v_combinationsearch.jspx")
			public void combinationsearch(Long storeId,Long combinationtypeId,Long combinationbrandId,String combinationproductName,
					HttpServletRequest request, HttpServletResponse response,
					ModelMap model) {
				ShopMember member=CmsUtils.getMember(request);
				Store store=member.getStore();
				List<Product> list = manager.getList(store.getId(),combinationtypeId, combinationbrandId, combinationproductName);
				JSONObject json=new JSONObject();
				try {
					for (int i=0 ,j=list.size(); i < j; i++) {
							json.append(list.get(i).getId() + "", list.get(i).getName());
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				ResponseUtils.renderJson(response, json.toString());
			}
	
	private void saveProductFash(Product bean,String[] nature,Boolean[] isDefaults,Integer[] stockCounts,
			Double[] salePrices,Double[] marketPrices,Double[] costPrices ){
		if(nature!=null){
			for(int i =0;i<nature.length;i++){
				String[] arr;
				ProductFashion pfash=new ProductFashion();
				pfash.setCreateTime(new Date());
				pfash.setIsDefault(isDefaults[i]);
				pfash.setStockCount(stockCounts[i]);
				pfash.setMarketPrice(marketPrices[i]);
				pfash.setSalePrice(salePrices[i]);
				pfash.setCostPrice(costPrices[i]);
				pfash.setProductId(bean);
				pfash.setNature(nature[i]);
				arr=nature[i].split("_");
				ProductFashion fashion = productFashionMng.save(pfash,arr);
				productFashionMng.addStandard(fashion,arr);
				if(isDefaults[i]){
					bean.setCostPrice(costPrices[i]);
					bean.setMarketPrice(marketPrices[i]);
					bean.setSalePrice(salePrices[i]);
				    manager.update(bean);
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/product/v_edit.jspx",method = RequestMethod.GET)
	public String edit(Long id,Long ctgId,Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		//用户没有注册店铺，跳转到店铺注册页
		if(store==null){
			return "redirect:registerStore.jspx";
		}
		Product product = manager.findById(id);
		List<ProductStandard> psList = productStandardMng.findByProductId(id);
		String productKeywords = StringUtils.join(product.getKeywords(),LIST_SPLIT);// 模型项列表
		Category category= product.getCategory(); 	
		List<StandardType> standardTypeList = standardTypeMng.getList(category.getId());
		List<ProductTypeProperty> itemList = productTypePropertyMng.getList(category.getType().getId(), false);
		List<ProductExended> pelist=product.getExendeds();
		List<Exended> exendeds = exendedMng.getList(category.getType().getId());
		Map map= new HashMap(); 
		Map map1= new HashMap(); 
		int num = exendeds.size();
	    for(int i=0;i<num;i++){
			map.put(exendeds.get(i).getId().toString(), exendeds.get(i).getItems());
			map1.put(exendeds.get(i).getId().toString(), exendeds.get(i));
		}
	    Map map2=new HashMap();
      	for(int i=0;i<pelist.size();i++){
		   map2.put(pelist.get(i).getName(), pelist.get(i).getValue());
	    }
      	List<ProductType> typeList = productTypeMng.getList(1L);
		List<Brand> brandList = brandMng.getAllList();
		model.addAttribute("brandList", brandList);
		model.addAttribute("typeList", typeList);
	    model.addAttribute("map2", map2);
		model.addAttribute("map", map);
		model.addAttribute("map1", map1);
		model.addAttribute("productKeywords", productKeywords);
		model.addAttribute("tagList", productTagMng.getList(SiteUtils.getWebId(request)));
		model.addAttribute("categoryList", categoryMng.getList(SiteUtils.getWebId(request)));
		model.addAttribute("standardTypeList",standardTypeList);
		model.addAttribute("category", category);
		model.addAttribute("product", product);
		model.addAttribute("ctgId", ctgId);
		model.addAttribute("itemList", itemList);
		model.addAttribute("psList",psList);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,
				PRODUCT_EDIT), request);
	}
	
	@RequestMapping(value="/product/o_update.jspx",method=RequestMethod.POST)
	public String update(Product bean, ProductExt ext, Long ctgId,Long promoteId,Long[] storeCategoryIds,
			Long[] storeIds,Long[] picture,Long[] fashId,String[] nature,String[] colorImg,Long[] character,
			String fashionSwitchPic[],Boolean[] isDefaults,Long[] colors,Long[] measures,Integer stockCounts[],Integer[] saleCounts,
			Double[] salePrices,Double[] marketPrices,Double[] costPrices,
			Long brandId, Long[] tagIds, String productKeywords,String rightlist,String combinationrightlist, 
			@RequestParam(value = "file", required = false) MultipartFile file, Integer pageNo,
			HttpServletRequest request, ModelMap model) throws IOException {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		//用户没有注册店铺，跳转到店铺注册页
		if(store==null){
			return "redirect:registerStore.jspx";
		}
		productKeywords = StringUtils.replace(productKeywords, MessageResolver
				.getMessage(request, "product.keywords.split"), LIST_SPLIT);
		String[] keywords = StringUtils.split(productKeywords, LIST_SPLIT);
		Map<String, String> exended = RequestUtils.getRequestMap(request, "exended_");
		Map<String, String> attr = RequestUtils.getRequestMap(request, "attr_");
		List li=new ArrayList(exended.keySet());
		String[] names = new String[li.size()];
		String[] values =  new String[li.size()];
		for(int i=0;i<li.size();i++){
		    names[i]=(String) li.get(i);
		    values[i]=exended.get(li.get(i));
		}
		if(stockCounts!=null){
	    	bean.setStockCount(getstockCounts(stockCounts));
	    }
		bean = manager.update(bean, ext, ctgId, brandId, promoteId,storeCategoryIds,tagIds, keywords,names,values,attr,
				fashionSwitchPic,file);
		manager.updateCorrelation(bean,getProductIds(rightlist));
		manager.updateCombination(bean,getProductIds(combinationrightlist));
		List<ProductStandard> pcList=productStandardMng.findByProductId(bean.getId());
		for(int j=0;j<pcList.size();j++){
			productStandardMng.deleteById(pcList.get(j).getId());
		}
		if(picture!=null){
			for(int i =0;i<picture.length;i++){
				ProductStandard ps=new ProductStandard();
				ps.setImgPath(colorImg[i]);
				ps.setType(standardMng.findById(picture[i]).getType());
				ps.setProduct(bean);
				ps.setStandard(standardMng.findById(picture[i]));
				ps.setDataType(true);
				productStandardMng.save(ps);
			}
		}
	   if(character!=null){
		   for(int i =0;i<character.length;i++){
				ProductStandard ps=new ProductStandard();
				ps.setType(standardMng.findById(character[i]).getType());
				ps.setProduct(bean);
				ps.setStandard(standardMng.findById(character[i]));
				ps.setDataType(false);
				productStandardMng.save(ps);
			}
	   }
		
		if(bean.getCategory().getColorsize()){
			java.util.Set<ProductFashion> pfList = bean.getFashions();
			if(fashId!=null){
				for(ProductFashion ps:pfList){
					if(!Arrays.asList(fashId).contains(ps.getId())){
						productFashionMng.deleteById(ps.getId());
					}
				}
			}else{
				for(ProductFashion ps:pfList){
					    productFashionMng.deleteById(ps.getId());
				}
			}
			updateProductFash(bean,fashId,nature,isDefaults,stockCounts,salePrices,marketPrices,costPrices);
		}
		String path = servletContext.getRealPath(Constants.LUCENE_JSPGOU);
		Directory dir = new SimpleFSDirectory(new File(path));
		try {
			luceneProductSvc.updateIndex(bean,dir);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		log.info("update Product. id={}.", bean.getId());
		String cl="tbg_16";
		return list(cl,ctgId,null,
				null,null,null,null,null,pageNo, request, model);
	}
	
	private void updateProductFash(Product bean,Long[] fashId,String[] nature,Boolean[] isDefaults,Integer[] stockCounts,
			Double[] salePrices,Double[] marketPrices,Double[] costPrices ){
		if(nature!=null){
			for(int i =0;i<nature.length;i++){
				String[] arr;
				ProductFashion pfash;
				if(fashId!=null&&i<fashId.length){
					pfash=productFashionMng.findById(fashId[i]);
					pfash.setCreateTime(new Date());
					pfash.setIsDefault(isDefaults[i]);
					pfash.setStockCount(stockCounts[i]);
					pfash.setMarketPrice(marketPrices[i]);
					pfash.setSalePrice(salePrices[i]);
					pfash.setCostPrice(costPrices[i]);
					pfash.setProductId(bean);
					pfash.setNature(nature[i]);
					arr=nature[i].split("_");
					productFashionMng.updateStandard(pfash, arr);
					if(isDefaults[i]){
						bean.setCostPrice(costPrices[i]);
						bean.setMarketPrice(marketPrices[i]);
						bean.setSalePrice(salePrices[i]);
						manager.update(bean);
					}
				}else{
					pfash = new ProductFashion();
					pfash.setCreateTime(new Date());
					pfash.setIsDefault(isDefaults[i]);
					pfash.setStockCount(stockCounts[i]);
					pfash.setMarketPrice(marketPrices[i]);
					pfash.setSalePrice(salePrices[i]);
					pfash.setCostPrice(costPrices[i]);
					pfash.setProductId(bean);
					pfash.setNature(nature[i]);
					arr=nature[i].split("_");
					ProductFashion fashion = productFashionMng.save(pfash,arr);
					productFashionMng.addStandard(fashion,arr);
					if(isDefaults[i]){
						bean.setCostPrice(costPrices[i]);
						bean.setMarketPrice(marketPrices[i]);
						bean.setSalePrice(salePrices[i]);
						manager.update(bean);
					}
				}
				
			}
		}
	}

	@RequestMapping(value = "/product/v_standardTypes_add.jspx")
	public String standardTypesAdd(Long categoryId,HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		    Website web=SiteUtils.getWeb(request);
		    List<StandardType> standardTypeList = standardTypeMng.getList(categoryId);
		    model.addAttribute("standardTypeList", standardTypeList);
		    model.addAttribute("digit", standardTypeList.size());
		    response.setHeader("Cache-Control", "no-cache");
		    response.setContentType("text/json;charset=UTF-8");
			ShopFrontHelper.setCommonData(request, model, web);
			return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,PRODUCT_STANDARDTYPES), request);
	}
	
	@RequestMapping("/product/product_categorychild.jspx")
	public void productCategoryChild(Long parentId, HttpServletRequest request,
			HttpServletResponse response)throws JSONException {
		Website web = SiteUtils.getWeb(request);
		JSONArray arr = new JSONArray();
		if (parentId != null) {
			List<Category> clist=categoryMng.getChildList(web.getId(), parentId);
			if(clist.size()>0){
				
				JSONObject o;
				for (Category t : clist) {
					   o= new JSONObject();
					   o.put("success", true);
					   o.put("id", t.getId());
					   o.put("name", t.getName());
					   arr.put(o);
				 }
			}else{
				Category category=categoryMng.findById(parentId);
				List<Brand> blist=new ArrayList<Brand>(category.getBrands());
				JSONObject o;
				for(Brand brand:blist){
					 o= new JSONObject();
					 o.put("success", false);
					 o.put("id", brand.getId());
					 o.put("name", brand.getName());
					 arr.put(o);
				}
			}
		}
		ResponseUtils.renderJson(response, arr.toString());
	}
	
	public Long[] getProductIds(String rightlist){
		String[] arr;
		arr = rightlist.split(",");
		Long productIds[]  = new Long[arr.length] ; 
		for(int i=0,j=arr.length;i<j;i++){
			if(!arr[i].equals("")){
				productIds[i] = Long.parseLong(arr[i]);
			}
		}
		return productIds;
	}
	
	@RequestMapping("/product/o_delete.jspx")
	public String delete(Long[] ids, Long ctgId, Boolean isRecommend,
			Boolean isSpecial, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		Product[] beans;
		try {
			beans = manager.deleteByIds(ids);
			for (Product bean : beans) {
				log.info("delete Product. id={}", bean.getId());
			}
		} catch (Exception e) {
		}
		return "redirect:v_list.jspx";
	}
	
	@RequestMapping(value = "/product/a_update.jspx")
	public String update(Long id,Integer pageNo,HttpServletRequest request,ModelMap model){
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		//用户没有注册店铺，跳转到店铺注册页
		if(store==null){
			return "redirect:registerStore.jspx";
		}
		
		Product bean=manager.findById(id);
		if(bean.getOnSale()==false){
			bean.setOnSale(true);
	
		}else{
			bean.setOnSale(false);
		}
		
		bean = manager.update(bean);
		log.info("update Product. id={}.", bean.getId());
		return "redirect:v_list.jspx";
		
	}
	
	@RequestMapping("/product/v_shangjia.jspx")
	public String shangjia(Long[]ids,Integer pageNo, HttpServletRequest request,ModelMap model){
		for(Long id:ids){
			Product bean=manager.findById(id);
			bean.setOnSale(true);
			manager.update(bean);
		}
		return "redirect:v_list.jspx";
		
	}
	@RequestMapping("/product/v_xiajia.jspx")
	public String xiajia(Long[]ids,Integer pageNo, HttpServletRequest request,ModelMap model){
		for(Long id:ids){
			Product bean=manager.findById(id);
			bean.setOnSale(false);
			manager.update(bean);
		}
		return "redirect:v_list.jspx";
		
	}	
	@Autowired
	private ProductMng manager;
	@Autowired
	private PaymentMng paymentMng;
	@Autowired
	private PromoteMng promoteMng;
	@Autowired
	private ShippingMng shippingMng;
	@Autowired
	private StandardMng standardMng;
	@Autowired
	private CategoryMng categoryMng;
	@Autowired
	private ProductTagMng productTagMng;
	@Autowired
	private ProductFashionMng productFashionMng;
	@Autowired
	private LuceneProductSvc luceneProductSvc;
	@Autowired
	private ServletContext servletContext;
	@Autowired
	private ProductTypePropertyMng productTypePropertyMng;
	@Autowired
	private StandardTypeMng standardTypeMng;
	@Autowired
	private ExendedMng exendedMng;
	@Autowired
	private ProductStandardMng productStandardMng;
	@Autowired
	private BrandMng brandMng;
	@Autowired
	private ProductTypeMng productTypeMng;
	
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

}
